import request from "./request";
import OSS from 'ali-oss';

import { cryptoDecryptBase } from '@src/utils/encryption';

// 获取用户信息
export const getUser = async () => {
  return await request({
    url: '/userInfo/info',
    method: 'get',
    data: {}
  });
};


// 获取我邀请的用户
export const getMyInvited = async () => {
  return await request({
    url: '/invite/getMyInvited',
    method: 'get',
    data: {}
  });
};

// 获取我邀请的用户，用于饼图
export const getMyInvitedChart = async () => {
  return await request({
    url: '/invite/getMyInvitedChart',
    method: 'get',
    data: {}
  });
};

// 修改用户语言
export const editUserLangApi = async ({
  lang
}) => {
  // zhCN / zhTW / enUS

  const res = await request({
    url: `/user/lang/${lang}`,
    method: 'put'
  });

  return res;
}

/**
 * 文件上传阿里云
 * @param {File} files // 文件 或多文件数组
 * @param {string} filePath // 文件夹路径
 * @returns 
 */
export const uploadALiFile = async (files, filePath='') => {
  const ossRes = await request({
    url: '/auths/oss',
    method: 'get'
  })

  if (!ossRes) return false;

  const client = new OSS({
    cname: true,
    // endpoint: `oss-cn-hongkong.aliyuncs.com`,
    endpoint: `solution-supermarket.oss-cn-hongkong.aliyuncs.com`,
    accessKeyId: ossRes.accesskey_id,
    accessKeySecret: cryptoDecryptBase(ossRes.accesskey_secret),
    bucket: 'solution-supermarket'
  })

  // 单文件
  const uploadSingleFile = async (file) => {
    try {
      const path = filePath ? `/${filePath}/${file.name}` : file.name
      const result = await client.put(path, file);

      return result.url;
    } catch (error) {
      return null
    }
  };

  // 多文件
  const uploadMultipleFiles = async (files) => {
    const uploadPromises = files.map(file => uploadSingleFile(file));
    const urls = await Promise.all(uploadPromises);

    return urls.filter(url => !!url);
  };

  if (files instanceof File) {
    const url = await uploadSingleFile(files);
    return url ? [url] : [];
  } else if (Array.isArray(files)) {
    return await uploadMultipleFiles(files)
  }else {
    return false;
  }
}